package com.hhhn.wk.main.tab3.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.main.tab2.entity.Commodity;
import com.hhhn.wk.main.tab4.address.AddressAllActivity;
import com.hhhn.wk.main.tab4.address.entity.Address;
import com.hhhn.wk.pay.PayActivity;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.DesUtils;
import com.hhhn.wk.utils.mi.AES;
import com.hhhn.wk.widget.adapter.MyAdaper;
import com.hhhn.wk.widget.adapter.ViewHolder;
import com.hhhn.wk.widget.customview.MyListView;

import org.json.JSONArray;
import org.json.JSONException;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

import static com.hhhn.wk.main.fragment.TabFragment02.Classify_allTypeFragment1.TAG;


/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/3/17 0017    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 确认订单---购物车
 * * * * * * * * * * * */
public class ConfirmOrderCartActivity extends BaseActivity {
    private BaseActivity activity;
    private TextView tv_title;
    private String tmpTotal="";//商品金额（不含运费）
    private String tmpFreight="";//商品总的运费
    private String shipAddressId="";//收货地址id
    private TextView tv_addressName;//收货姓名
    private TextView tv_addressPhone;//收货手机号
    private TextView tv_address;//收货地址
    private LinearLayout ll_Address_p;//收货地址有
    private LinearLayout ll_Address_n;//收货地址无
    public static ArrayList<Address> mArrayListAddress=new ArrayList<Address>();
    int type=0;//跳转类型
    ArrayList<String> cartIdList =new ArrayList<>();
    /*商品列表*/
    private ArrayList<Commodity> commodityList =new ArrayList<>();//商品数组
    private MyAdaper<Commodity> mAdapter;
    private MyListView mLoadListView;
    private TextView tv_goodsMoney;//商品金额
    private TextView tv_goodsfreight;//运费
    private TextView tv_goPay;//下单
    private TextView tv_total;//下单

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mArrayListAddress.size() == 0) {
                        ll_Address_n.setVisibility(View.VISIBLE);
                        ll_Address_p.setVisibility(View.GONE);
                    } else {
                        ll_Address_n.setVisibility(View.GONE);
                        ll_Address_p.setVisibility(View.VISIBLE);
                        loadAddrssData();
                    }
                    break;
                case 2:
                    loadData();
                    break;
//                case 3:
//                    mPullToRefreshLayout.setVisibility(View.GONE);
//                    ll_empty.setVisibility(View.VISIBLE);
////                    mPullToRefreshLayout.showView(ViewStatus.ERROR_STATUS);////网络错误
//                    dismissLoad();
//                    break;
            }
            super.handleMessage(msg);
        }
    };
    //加载地址
    private void loadAddrssData() {
        shipAddressId=mArrayListAddress.get(0).getId();
        tv_addressName.setText(mArrayListAddress.get(0).getName());
        tv_addressPhone.setText(mArrayListAddress.get(0).getPhone());
        tv_address.setText(mArrayListAddress.get(0).getProvince()+mArrayListAddress.get(0).getCity()+mArrayListAddress.get(0).getTown()+mArrayListAddress.get(0).getAddress());

    }

    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_confirm_order);
        activity=this;

        Intent intent=getIntent();
         type = intent.getIntExtra("type", 1);//1购物车跳转   2商品直接跳转
        if (type==1){
            cartIdList= intent.getStringArrayListExtra("cartIdList");
        }else {
        }
    }
    @Override
    protected void initView() {
        tv_total=findViewById(R.id.tv_total);
        tv_title=findViewById(R.id.tv_title);
        tv_title.setText("确认订单");
        tv_addressName=findViewById(R.id.tv_addressName);
        tv_addressPhone=findViewById(R.id.tv_addressPhone);
        tv_address=findViewById(R.id.tv_address);
        ll_Address_p=findViewById(R.id.ll_Address_p);
        ll_Address_n=findViewById(R.id.ll_Address_n);
        mLoadListView=findViewById(R.id.mLoadListView);
        tv_goodsMoney=findViewById(R.id.tv_goodsMoney);
        tv_goodsfreight=findViewById(R.id.tv_goodsfreight);
        tv_goPay=findViewById(R.id.tv_goPay);
    }
    @Override
    protected void initData() {
        getJSON();
        getShop();
    }

    @Override
    protected void initClick() {
        ll_Address_n.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(activity,AddressAllActivity.class);
                intent.putExtra("type",1);
                startActivityForResult(intent,1);
            }
        });
        ll_Address_p.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(activity,AddressAllActivity.class);
                intent.putExtra("type",1);
                startActivityForResult(intent,1);
            }
        });
        tv_goPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (type==1){
                    getXiadan();
                }else {

                }
            }
        });
    }
    //查询收货地址
    public void getJSON() {
        RequestParams params = AllPublic.getParams(activity, "/showShipAddress", true);
        params.addParameter("cmUserId",activity.getUser().getUid());/*用户Id*/
        Log.d("查询收货地址", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("查询收货地址：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray records = jsonObject.getJSONArray("data");
                        Address myOrder=null;
                        for (int i=0;i<records.length();i++){
                            myOrder=new Address();
                            JSONObject object = records.getJSONObject(i);
                            String addressId = object.has("id") ? object.getString("id") : "";//id
                            String province = object.has("province") ? object.getString("province") : "";
                            String city = object.has("city") ? object.getString("city") : "";
                            String town = object.has("town") ? object.getString("town") : "";
                            String address = object.has("address") ? object.getString("address") : "";
                            String userName = object.has("shipName") ? object.getString("shipName") : "";//
                            String phone = object.has("shipTel") ? object.getString("shipTel") : "";//
                            int isShow = object.has("isDefault") ? object.getInt("isDefault") : 100902;//100901默认   100902不是默认
//                            if (isShow==100901){
                                myOrder.setProvince(province);
                                myOrder.setTown(town);
                                myOrder.setCity(city);
                                myOrder.setDef(isShow);
                                myOrder.setId(addressId);
                                myOrder.setAddress(address);
                                myOrder.setName(userName);
                                myOrder.setPhone(phone);
                                mArrayListAddress.add(myOrder);
//                            }
                        }
                        handler.sendEmptyMessage(1);
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==1){
            String name = data.getStringExtra("name");
            String phone = data.getStringExtra("phone");
            String address = data.getStringExtra("address");
            shipAddressId = data.getStringExtra("shipAddressId");

            tv_addressName.setText(name);
            tv_addressPhone.setText(phone);
            tv_address.setText(address);
            ll_Address_n.setVisibility(View.GONE);
            ll_Address_p.setVisibility(View.VISIBLE);
        }
    }
    //确认订单-查询商品
    public void getShop() {
        showLoad();
        RequestParams  params = AllPublic.getParamsProductOrder(activity, "/confirmMultiOrders", false);
//        params.addParameter("cmUserId",activity.getUser().getUid());
//        params.addParameter("shopCarList",cartIdList);
//        Log.d(" 确认订单-查询商品", "getJSON: "+cartIdList);
//        Log.d(" 确认订单-查询商品", "getJSON: "+cartIdList.toString());
//        Log.d(" 确认订单-查询商品", "getJSON: "+cartIdList.toArray());
//        Log.d(" 确认订单-查询商品", "getJSON: "+params);
        com.alibaba.fastjson.JSONObject person=new com.alibaba.fastjson.JSONObject();
        person.put("cmUserId",activity.getUser().getUid());
        person.put("shopCarList",cartIdList);
        AES aes = AllPublic.jsonDesPackagF(person);
        Log.e(TAG, "data: "+aes.getData());
        Log.e(TAG, "key: "+aes.getKey());
        params.addParameter("data",aes.getData());
        params.addParameter("key",aes.getKey());
        Log.e(TAG, "getShop: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String decode) {
                String result = AllPublic.jsonDesDecode(decode);//解密
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        JSONArray records = data.getJSONArray("productList");
                        Commodity commodity=null;
//                        if (records.length()< Config.ROWS){
//                            isWU=true;
//                        }
                        for (int i=0;i<records.length();i++){
                            commodity=new Commodity();
                            JSONObject object = records.getJSONObject(i);
                            String commodityid = object.has("id") ? object.getString("id") : "";//id
                            String image = object.has("productImage") ? object.getString("productImage") : "";//产品图片
                            String productName = object.has("productName") ? object.getString("productName") : "";//产品名称
                            String productPrice = object.has("productPrice") ? object.getString("productPrice") : "";//价格
                            String productNum = object.has("productNum") ? object.getString("productNum") : "";//商品库存-剩余库存
                            commodity.setCommodityID(commodityid);
                            commodity.setCommodityImg(image);
                            commodity.setCommodityName(productName);
                            commodity.setPriceNew(productPrice);
                            commodity.setProductNum(productNum);
                            commodityList.add(commodity);
                        }
                        tmpTotal=data.getString("tmpTotal");
                        tmpFreight=data.getString("freightTotal");
                        tv_goodsMoney.setText("￥："+data.getString("tmpTotal"));
                        tv_goodsfreight.setText("￥："+data.getString("freightTotal"));
                        tv_total.setText("总计￥："+data.getString("total"));
                        handler.sendEmptyMessage(2);
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                dismissLoad();
            }
            @Override
            public void onFinished() {

                dismissLoad();
            }
        });
    }
    private void loadData() {
        if (mAdapter==null){
            mAdapter=new MyAdaper<Commodity>(commodityList,R.layout.shop_list) {
                @Override
                public void bindView(ViewHolder holder, Commodity obj, int position) {
                    holder.setImageyuan(R.id.iv_CommodityImg,obj.getCommodityImg());//图片
                    holder.setText(R.id.iv_CommodityName,obj.getCommodityName());
                    holder.setText(R.id.tv_priceNew,"￥"+AllPublic.priceGSH(obj.getPriceNew()));
                    holder.setText(R.id.tv_priceNumber,"X"+obj.getProductNum());
                }
            };
            mLoadListView.setAdapter(mAdapter);
        }else {
            mAdapter.notifyDataSetChanged();
        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (commodityList!=null){
            commodityList.clear();
        }
        if (mAdapter!=null){
            mAdapter=null;
        }
    }
    //下单--购物车
    public void getXiadan() {
        showLoad();
        RequestParams  params = AllPublic.getParamsProductOrder(activity, "/saveProductOrderFromShopCar", false);
//        params.addParameter("cmUserId",activity.getUser().getUid());
//        params.addParameter("shopCarList",cartIdList);
//        params.addParameter("shipAddressId",shipAddressId);//收货地址ID
//        params.addParameter("tmpTotal",tmpTotal);//商品金额（不含运费）
//        params.addParameter("tmpFreight",tmpFreight);//商品总的运费
        com.alibaba.fastjson.JSONObject person=new com.alibaba.fastjson.JSONObject();
        person.put("cmUserId",activity.getUser().getUid());
        person.put("shopCarList",cartIdList);

        person.put("shipAddressId",shipAddressId);//收货地址ID
        person.put("tmpTotal",tmpTotal);//商品金额（不含运费）
        person.put("tmpFreight",tmpFreight);//商品总的运费

        AES aes = AllPublic.jsonDesPackagF(person);
        params.addParameter("data",aes.getData());
        params.addParameter("key",aes.getKey());
//            String string="";
//            Log.e(TAG, "JOSN封装:"+person.toJSONString());
//            Log.e(TAG, "JOSN封装:"+person.toString());
//            DesUtils desObj = new DesUtils();
//            string = desObj.strEnc(person.toString(),DesUtils.key1, DesUtils.key2, DesUtils.key3);//加密
//            Log.e(TAG, "JOSN封装--加密:"+string);
//
//            params.addParameter("body",string);

        Log.e(TAG, "getShop: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String decode) {
                String result = AllPublic.jsonDesDecode(decode);//解密
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONObject data = jsonObject.getJSONObject("data");
                            String orderCode = data.has("orderCode") ? data.getString("orderCode") : "";//订单id
                            String orderId = data.has("id") ? data.getString("id") : "";//订单id
                            String money = data.has("money") ? data.getString("money") : "";//总计
                            String deductibleAmount = data.has("deductibleAmount") ? data.getString("deductibleAmount") : "";//
                        String actualPayment = data.has("actualPayment") ? data.getString("actualPayment") : "";//实际
                            Intent intent=new Intent(activity, PayActivity.class);
                            intent.putExtra("orderId",orderId);
                            intent.putExtra("orderCode",orderCode);
                            intent.putExtra("money",money);
                        intent.putExtra("deductibleAmount",deductibleAmount);
                        intent.putExtra("shiji",actualPayment);
                            startActivity(intent);
                            finish();
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                dismissLoad();
            }
            @Override
            public void onFinished() {

                dismissLoad();
            }
        });
    }






}
